package cn.com.zhaoweiping.ie.handler;

import cn.com.zhaoweiping.ie.ExcelField.CommentVo;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.AbstractCellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

/**
 * 单元格注释<br>
 *
 * @author 冰羽
 * @version 2.2.0
 */
public class CellCommentHandler extends AbstractCellWriteHandler {

  private List<CommentVo> commentVos;

  public CellCommentHandler(List<CommentVo> commentVos) {
    this.commentVos = commentVos;
  }

  @Override
  public void afterCellDispose(
      WriteSheetHolder writeSheetHolder,
      WriteTableHolder writeTableHolder,
      List<CellData> cellDataList,
      Cell cell,
      Head head,
      Integer relativeRowIndex,
      Boolean isHead) {
    boolean needSetWidth = isHead || CollectionUtil.isNotEmpty(cellDataList);
    if (needSetWidth && CollectionUtil.isNotEmpty(commentVos)) {
      int rowIndex = cell.getRowIndex();
      int colIndex = cell.getColumnIndex();

      List<CommentVo> vos =
          commentVos.stream()
              .filter(
                  vo -> vo != null && vo.getRowIndex() == rowIndex && vo.getColIndex() == colIndex)
              .collect(Collectors.toList());

      if (CollectionUtil.isNotEmpty(vos)) {
        CommentVo vo = vos.stream().findFirst().get();
        if (StrUtil.isNotEmpty(vo.getText())) {
          Sheet sheet = cell.getSheet();
          ClientAnchor anchor = new XSSFClientAnchor();

          anchor.setDx1(0);
          anchor.setDy1(0);
          anchor.setDx2(0);
          anchor.setDy2(0);
          anchor.setRow1(rowIndex);
          anchor.setCol1(colIndex);
          anchor.setRow2(rowIndex + vo.getRowOffset());
          anchor.setCol2(colIndex + vo.getColOffset());

          Drawing drawing = sheet.createDrawingPatriarch();

          Comment comment = drawing.createCellComment(anchor);
          comment.setString(new XSSFRichTextString(vo.getText()));
          if (StrUtil.isNotEmpty(vo.getAuthor())) {
            comment.setAuthor(vo.getAuthor());
          }
          cell.setCellComment(comment);
        }
      }
    }
  }
}
